<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-button type="primary" @click="showAddCategoryDialog">添加分类</el-button>
      <!-- 表格 -->
      <tree-table
        :data="goodsCategories"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        class="treeTable"
        show-index
        index-text="#"
        border
      >
        <!-- 这里用了模板插槽 -->
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted==true"></i>
          <i class="el-icon-error" v-if="scope.row.cat_deleted==false"></i>
        </template>
        <template slot="level" slot-scope="scope">
          <el-tag type="success" v-if="scope.row.cat_level==0">一级</el-tag>
          <el-tag type="danger" v-if="scope.row.cat_level==1">二级</el-tag>
          <el-tag type="info" v-if="scope.row.cat_level==2">三级</el-tag>
        </template>
        <template slot="control" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="showEditCateDialog(scope.row.cat_id)"
          >编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" @click="delCategory(scope.row)">删除</el-button>
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getCategoriesParams.pagenum"
        :page-sizes="[2,4,5,8,10]"
        :page-size="getCategoriesParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCategories"
      ></el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCategoryDialogVisible"
      width="40%"
      @close="delAddCategoryForm"
    >
      <el-form :model="addCategoryForm" ref="addCategoryRef" :rules="rules">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCategoryForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!-- 级联选择器 -->
          <!-- option指定数据源,v-model绑定一个数组，prop配置value将id项作为标识 ,clearable支持清空选择-->
          <el-cascader
            :options="parentCateList"
            :props="parentOption"
            v-model="selectParentCate"
            @change="parentCateChange"
            expand-trigger="hover"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAddCategory">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editCatedialogVisible"
      width="40%"
      @close="delEditCateForm"
    >
      <el-form :model="editCateForm" ref="editCateRef" :rules="rules">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doEditCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      goodsCategories: [],
      getCategoriesParams: {
        type: [1, 2, 3],
        pagenum: 1,
        pagesize: 8
      },
      totalCategories: 0,
      // 树形表格各列配置
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        // 是否有效这里用了作用域插槽,type类型设置为模板列，isok是模板名称
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'isok'
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'level'
        },
        { label: '操作', type: 'template', template: 'control' }
      ],
      addCategoryDialogVisible: false,
      addCategoryForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
        // 默认一级分类
      },
      rules: {
        cat_name: [{ required: true, message: '必填项', trigger: 'blur' }]
      },
      // 父级分类列表
      parentCateList: [],
      // 级联选择器配置对象
      parentOption: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true // 是否严格的遵守父子节点不互相关联
      },
      // 父级分类被选择的id组成的数组
      selectParentCate: [],
      // 修改分类名
      editCateForm: {
        cat_name: ''
      },
      editCatedialogVisible: false,
      // 要修改的分类名的id
      editCateID: ''
    }
  },
  created() {
    this.getGoodsCategories()
  },
  methods: {
    async getGoodsCategories() {
      const { data: ret } = await this.$http.get('categories', {
        params: this.getCategoriesParams
      })
      if (ret.meta.status !== 200) return this.$mesage.error(ret.meta.msg)
      this.goodsCategories = ret.data.result
      this.totalCategories = ret.data.total
    },
    handleSizeChange(e) {
      this.getCategoriesParams.pagesize = e
      this.getGoodsCategories()
    },
    handleCurrentChange(e) {
      this.getCategoriesParams.pagenum = e
      this.getGoodsCategories()
    },
    showAddCategoryDialog() {
      this.getParentCateList()
      this.addCategoryDialogVisible = true
    },
    doAddCategory() {
      // 提交添加的分类
      console.log(this.addCategoryForm)
      try {
        this.$refs.addCategoryRef.validate(async val => {
          if (!val) return
          const { data: ret } = await this.$http.post(
            'categories',
            this.addCategoryForm
          )
          if (ret.meta.status !== 201) return this.$message.error(ret.meta.msg)
          this.$message.success(ret.meta.msg)
          this.addCategoryDialogVisible = false
          this.getGoodsCategories()
        })
      } catch (err) {
        console.log(err)
      }
    },
    delAddCategoryForm() {
      this.$refs.addCategoryRef.resetFields()
      // 清空父级选择的id
      this.selectParentCate = []
      // 清空pid和level
      this.addCategoryForm.cat_pid = 0
      this.addCategoryForm.cat_level = 0
    },
    async getParentCateList() {
      // 获取父级分类表
      const { data: ret } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (ret.meta.status !== 200) return this.mesage.error(ret.meta.msg)
      this.parentCateList = ret.data
      console.log(this.parentCateList)
    },
    parentCateChange() {
      // 级联选择器选择发生变化时更新cat_pid，cat_level
      // 父级id是数组的最后一个id,数组里可能是1个也可能是两个
      if (!this.selectParentCate) {
        this.addCategoryForm.cat_pid = 0
        this.addCategoryForm.cat_level = 0
      }
      this.addCategoryForm.cat_pid = this.selectParentCate[
        this.selectParentCate.length - 1
      ]
      this.addCategoryForm.cat_level = this.selectParentCate.length
    },
    delCategory(row) {
      // 删除分类
      this.$confirm('确认永久删除此分类？确认继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: ret } = await this.$http.delete(
            'categories/' + row.cat_id
          )
          if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
          this.$message.success(ret.meta.msg)
          this.getGoodsCategories()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async showEditCateDialog(id) {
      // 显示修改分类对话框时传递id
      this.editCatedialogVisible = true
      this.editCateID = id
      const { data: ret } = await this.$http.get('categories/' + id)
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.editCateForm.cat_name = ret.data.cat_name
    },
    doEditCate() {
      // 完成修改分类名
      this.$refs.editCateRef.validate(async val => {
        console.log(val)
        if (!val) return
        const { data: ret } = await this.$http.put(
          'categories/' + this.editCateID,
          this.editCateForm
        )
        if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
        this.$message.success(ret.meta.msg)
        this.getGoodsCategories()
        this.editCatedialogVisible = false
      })
    },
    delEditCateForm() {
      // 清空修改分类表单
      this.$refs.editCateRef.resetFields()
    }
  }
}
</script>

<style lang='less' scoped>
.treeTable {
  margin: 10px 0;
  font-size: 16px;
}
.el-cascader {
  width: 100%;
}
</style>
